package com.tarena.csmall.seckill.checker;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import com.tarena.csmall.seckill.service.SeckillSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@ComponentScan
@Order(300)
public class RedisStockChecker implements SeckillCommitChecker{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void check(SeckillOrderAddDTO dto, String randCode) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        Long skuId=dto.getSeckillOrderItemAddDTO().getSkuId();
        //4. 减库存 如果减库存成功 发送消息,否则不发生 针对 sku的库存在redis存储结构string 利用incr decr
        // seckill:sku:stock:skuId 100 当前数字还没有,因为预热的时候没有考虑减库存的数据
        Long decrement = opsForValue.decrement(SeckillSkuService.SECKILL_SKU_STOCK_PREFIX + skuId, 1);
        // 如果返回值<0 说明库存不足,这里允许用户高并发请求的时候 将redis中的库存减到负数,没有限制最小是0
        if(decrement<0){
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"库存不足");
        }
    }
}
